package fourFragment.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.xuegengwang.xuegengwang.R;
import com.example.xuegengwang.xuegengwang.bean.Userbean;
import com.foamtrace.photopicker.ImageCaptureManager;
import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.PhotoPreviewActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;

import common.BaseActivity;
import common.Constant;
import https.InterNetController;
import https.UpLoadFileController;
import topic.adapter.DeliverCommentGridViewAdapter;
import utils.BitmapUtils;
import utils.DateUtils;
import utils.PickerUtils;
import view.MyConfirmDialog;
import view.MyImageLoader;
import utils.MyLogUtils;
import view.MyOptionPicker;

/**
 * Created by Administrator on 2017/3/30.
 * 个人信息修改
 */
@ContentView(R.layout.personal_info)
public class PersonalInfo extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.personal_info_item1)
    private RelativeLayout personal_info_item1;
    @ViewInject(R.id.personal_info_item2)
    private RelativeLayout personal_info_item2;
    @ViewInject(R.id.personal_info_item3)
    private RelativeLayout personal_info_item3;
    @ViewInject(R.id.personal_info_item4)
    private RelativeLayout personal_info_item4;
    @ViewInject(R.id.personal_info_headima)
    private RoundedImageView personal_info_headima;
    @ViewInject(R.id.personal_info_nickname)
    private TextView personal_info_nickname;
    @ViewInject(R.id.personal_info_info)
    private TextView personal_info_info;
    @ViewInject(R.id.personal_info_back)
    private ImageView personal_info_back;
    @ViewInject(R.id.personal_info_save)
    private TextView personal_info_save;

    private ImageCaptureManager captureManager;
    //resultcode
    private final int REQUEST_CAMERA_CODE = 0;
    private final int REQUEST_PREVIEW_CODE = 2;
    private final int CROP_PICTURE = 3;
    private final int MODIFY_NICK_NAME = 4;
    private ArrayList<String> photoPaths1 = new ArrayList<>();//图片路径,用于进入多选框用的

    private String exam_year = "";
    private String nick_name = "";
    private String head_url = "";
    //网络返回的flag
    private final int COMPLETEINFO = 1;
    private final int GETDATA = 0;
    private final int UPLOAD_IMA = 2;

    private static final String TAG = "PersonalInfo";

    private String tempHeadImaPath;
    private ArrayList<String> examYearList;//高考年份列表,当前向后推三年

    private Uri imageUri;


    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS:
                    switch (msg.arg1) {
                        case GETDATA:
                            Gson gson = new Gson();
                            Userbean userbean = gson.fromJson((String) msg.obj, Userbean.class);
                            if (userbean != null) {
                                Userbean.UserBean user = userbean.getUser();
                                if (user != null) {
                                    personal_info_nickname.setText(user.getName());
                                    personal_info_info.setText(user.getExam_year());
                                    MyImageLoader.showImage(user.getHeadimgurl(), personal_info_headima);
                                }
                            }
                            break;
                        case COMPLETEINFO:
                            PersonalInfo.this.setResult(2);
                            PersonalInfo.this.finish();
                            break;
                        case UPLOAD_IMA:
                            try {
                                JSONObject jsonObject = new JSONObject((String) msg.obj);
                                String url = jsonObject.getString("url");
                                if (!TextUtils.isEmpty(url)) {
                                    head_url = url;
                                }
                                BitmapUtils.deleteBitmapFile(tempHeadImaPath);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            completeInfo();
                            break;
                        default:
                            break;

                    }
                    break;

                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
    }

    private void initView() {
        Bitmap bitmap = getIntent().getParcelableExtra("headIma");
        String name = getIntent().getStringExtra("name");
        String year = getIntent().getStringExtra("year");
        personal_info_nickname.setText(name);
        personal_info_info.setText(year);
        personal_info_headima.setImageBitmap(bitmap);
        personal_info_item1.setOnClickListener(this);
        personal_info_item2.setOnClickListener(this);
        personal_info_item3.setOnClickListener(this);
        personal_info_item4.setOnClickListener(this);
        personal_info_save.setOnClickListener(this);
        personal_info_back.setOnClickListener(this);
    }


    private void initData() {
        examYearList = new ArrayList<>();
        String year = DateUtils.getYear();
        examYearList.add(year);//今年
        int i = Integer.parseInt(year);
        i += 1;
        String s = String.valueOf(i);
        examYearList.add(s);//明年
        i += 1;
        String s1 = String.valueOf(i);
        examYearList.add(s1);//后年

    }

    @Override
    public void onClick(View v) {
        Intent i = new Intent();
        switch (v.getId()) {
            case R.id.personal_info_item1:
                //修改头像
                choseImage();
                break;
            case R.id.personal_info_item2:
                //修改昵称
                i.setClass(PersonalInfo.this, ModifyNickName.class);
                i.putExtra("nickName", nick_name);
                startActivityForResult(i, MODIFY_NICK_NAME);
                break;
            case R.id.personal_info_item3:
                //修改高考年份
                MyOptionPicker myOptionPicker = PickerUtils.showSelector(PersonalInfo.this, examYearList);
                myOptionPicker.setOnOptionPickListener(new MyOptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(String option) {
                        exam_year = option;
                        personal_info_info.setText(option);
                    }
                });
                break;
            case R.id.personal_info_item4:
                //修改密码
                i.setClass(PersonalInfo.this, ModifyPwd.class);
                startActivity(i);
                break;
            case R.id.personal_info_back:
                if(!TextUtils.isEmpty(exam_year)||!TextUtils.isEmpty(nick_name)||!TextUtils.isEmpty(head_url)||imageUri != null) {

                    MyConfirmDialog myConfirmDialog = new MyConfirmDialog(this, "是否保存修改的信息？", "保存", "不保存");
                    myConfirmDialog.setCancelListener(new MyConfirmDialog.CancelListener() {
                        @Override
                        public void cancel() {
                            PersonalInfo.this.finish();
                        }
                    });
                    myConfirmDialog.setConfirmListener(new MyConfirmDialog.ConfirmListener() {
                        @Override
                        public void confirm() {
                            if (imageUri != null) {
                                upLoadIma();
                            } else {
                                completeInfo();
                            }
                        }
                    });
                    myConfirmDialog.show();
                }else{
                    this.finish();
                }
                break;
            case R.id.personal_info_save:
                if (imageUri != null) {
                    upLoadIma();
                } else {
                    completeInfo();
                }
                break;
            default:
                break;
        }
    }
    private void upLoadIma() {
        if (!TextUtils.isEmpty(imageUri.getPath())) {
            BitmapUtils.saveBitmapFile(imageUri.getPath(), new DeliverCommentGridViewAdapter.LocalImgComplete() {
                @Override
                public void localImgComplete(File file) {
                    if (file != null) {
                        new UpLoadFileController(PersonalInfo.this, Constant.UPLOADIMAGE, myHandler, null, file, UPLOAD_IMA);
                    }
                }
            }, tempHeadImaPath);
        }
    }

    //提交修改的个人信息
    private void completeInfo() {
        HashMap<String, String> hashMap = new HashMap<>();
        if (!TextUtils.isEmpty(personal_info_info.getText().toString())) {
            hashMap.put("exam_year", personal_info_info.getText().toString());
        }
        if (!TextUtils.isEmpty(personal_info_nickname.getText().toString())) {
            hashMap.put("name", personal_info_nickname.getText().toString());
        }
        if (!TextUtils.isEmpty(head_url)) {
            hashMap.put("headimgurl", head_url);
        }
        new InterNetController(this, Constant.COMPLETEINFO, myHandler, hashMap, COMPLETEINFO);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    refreshAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
                    break;
                // 拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();
                        // 照片地址
                        if (photoPaths1.size() < 1) {
                            String imagePath = captureManager.getCurrentPhotoPath();
                            photoPaths1.add(imagePath);
                        }
                    }
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    refreshAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT));
                    break;
                case CROP_PICTURE:
                    //裁剪完
                    Bitmap bitmap = decodeUriAsBitmap(imageUri);//decode bitmap
                    personal_info_headima.setImageBitmap(bitmap);
                    break;
                case MODIFY_NICK_NAME:
                    //修改昵称完成
                    nick_name = data.getStringExtra("nickName");
                    personal_info_nickname.setText(nick_name);
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (requestCode == CROP_PICTURE) {
                choseImage();
            }
        }
    }

    private void refreshAdpater(ArrayList<String> paths) {
        // 处理返回照片地址
        if (paths.size() > 0) {
            tempHeadImaPath = UpLoadFileController.getImageRemoteUrl();
            String tempPath = "/" + tempHeadImaPath + ".jpg";
            File dir = new File(Environment.getExternalStorageDirectory() + "/xuegengwang/picture/Cache/");//将要保存图片的路径
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir.getPath() + tempPath);//将要保存图片的路径
            imageUri = Uri.fromFile(file);
            Uri originalImageUri = Uri.fromFile(new File(paths.get(0)));
            Intent intent = new Intent();
            if (originalImageUri != null) {
                intent.setAction("com.android.camera.action.CROP");
                intent.setDataAndType(originalImageUri, "image/*");// mUri是已经选择的图片Uri
                intent.putExtra("crop", "true");
                intent.putExtra("scale", "true");
                intent.putExtra("outputX", 800);// 输出图片大小
                intent.putExtra("outputY", 800);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                intent.putExtra("return-data", false);
                this.startActivityForResult(intent, CROP_PICTURE);
            }
        }
    }

    @Override
    public void onBackPressed() {
        if(!TextUtils.isEmpty(exam_year)||!TextUtils.isEmpty(nick_name)||!TextUtils.isEmpty(head_url)||imageUri != null) {

            MyConfirmDialog myConfirmDialog = new MyConfirmDialog(this, "是否保存修改的信息？", "保存", "不保存");
            myConfirmDialog.setCancelListener(new MyConfirmDialog.CancelListener() {
                @Override
                public void cancel() {
                    PersonalInfo.this.finish();
                }
            });
            myConfirmDialog.setConfirmListener(new MyConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    if (imageUri != null) {
                        upLoadIma();
                    } else {
                        completeInfo();
                    }
                }
            });
            myConfirmDialog.show();
        }else{
            this.finish();
        }
    }

    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;

    }

    private void choseImage() {
        PhotoPickerIntent photoPickerIntent = new PhotoPickerIntent(PersonalInfo.this);
        photoPickerIntent.setSelectModel(SelectModel.MULTI);
        photoPickerIntent.setShowCarema(true); // 是否显示拍照， 默认false
        photoPickerIntent.setMaxTotal(1); // 最多选择照片数量，默认为9
        photoPickerIntent.setSelectedPaths(photoPaths1);
        startActivityForResult(photoPickerIntent, REQUEST_CAMERA_CODE);
    }

}
